class Gallery < ActiveRecord::Base
  has_and_belongs_to_many :artworks

  depends_on :content, :attrs => [:name, :url], 
             :as => :presentable, :dependent => :destroy

  def self.all
    find :all
  end

  def update_user_groups(new_user_group_ids = [])
    return if new_user_group_ids.empty?
    # Need to save this to modify sub_contents
    original_user_groups = content.user_groups.dup

		#
		# Removed previously associated user_groups if not checked this time.
		#
		content.user_groups.dup.each do |ug|
			unless new_user_group_ids.include?(ug.id)
				content.user_groups.delete(ug) 
			end
		end

		# 
		# Add in the new user_groups
		#
		new_user_group_ids.each do |id|
			next if content.user_group_ids.include?(id)
			content.user_groups << UserGroup.find(id)
		end

    artworks.each do |art|
      reset_contents_user_groups(art, original_user_groups, new_user_group_ids)
    end
  end # update_user_groups

  def reset_contents_user_groups(art, original_user_groups, new_user_group_ids)
		#
		# Removed user groups inherited from parent
		#
    original_user_groups.each do |oug|
      if art.user_group_ids.include?(oug.id)
        art.user_groups.delete(oug)
      end
    end

		# 
		# Add in the new user_groups from the parent
		#
		new_user_group_ids.each do |id|
			next if art.user_groups.include?(id)
			art.user_groups << UserGroup.find(id)
		end
  end # reset_contents_user_groups

end
